import MarkdownIt from 'markdown-it'
import anchor from 'markdown-it-anchor'
import { nanoid } from 'nanoid'
import md_hljs from 'markdown-it-highlightjs'

import hljs from 'highlight.js'
hljs.highlightAll()

// eslint-disable-next-line no-unused-vars
const AlexCollector = (md, options) => {
  const originalRender =
    md.renderer.rules.heading_open ||
    function (tokens, idx, options, env, self) {
      return self.renderToken(tokens, idx, options)
    }

  md.renderer.rules.heading_open = function (tokens, idx, options, env, self) {
    const level = tokens[idx].tag
    const titleIdx = idx + 1
    const title = tokens[titleIdx].content

    // 找到对应的nanoid
    const nanoid = tokens[idx].attrs.find((attr) => attr[0] === 'id')[1]

    if (!env.headers) {
      env.headers = []
    }

    env.headers.push({
      level: level,
      title: title,
      uuid: nanoid
    })

    return originalRender(tokens, idx, options, env, self)
  }
}

class Markdown {
  constructor(input) {
    this._data = input
    this.env = {}
    this.MarkdownIt = MarkdownIt()
      .use(AlexCollector)
      .use(anchor, {
        permalink: anchor.permalink.linkInsideHeader,
        slugify: () => nanoid(5),
        permalinkBefore: true,
        permalinkSymbol: '#',
        level: [1, 2, 3, 4]
      })
      .use(md_hljs, {
        inline: true,
        hljs: hljs
      })
  }

  title = () => {
    return this.env.headers.filter((item) => item.level === 'h1')[0]
  }
  toc_list = () => {
    return this.env.headers
  }

  content = () => {
    return this.MarkdownIt.render(this._data, this.env).replace(/<h1[^>]*>.*?<\/h1>/gs, '')
  }
}

export { Markdown }
